package cn.doitedu.web.controller;

import cn.doitedu.engine.StaticContext;
import cn.doitedu.engine.StaticContextV2;
import cn.doitedu.web.pojo.Rule;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class EngineController {

    @RequestMapping("/api/add_rule")
    public String addRule(String ruleId,String expression) throws IOException, ClassNotFoundException {
        HashMap<String, String> map = StaticContextV2.getOrRestoreRuleMap();
        // 将接收到的新增规则，放入规则容器
        if(map.containsKey(ruleId)) {
            return "rule_add_fail";
        }else {
            map.put(ruleId, expression);
            return "rule_add_success";
        }

    }


    @RequestMapping("/api/get_rules")
    @ResponseBody
    public List<Rule> listRules() throws IOException, ClassNotFoundException {

        HashMap<String, String> map = StaticContextV2.getOrRestoreRuleMap();

        ArrayList<Rule> rules = new ArrayList<>();

        for (Map.Entry<String, String> entry : map.entrySet()) {
            String ruleId = entry.getKey();
            String expression = entry.getValue();

            Rule rule = new Rule(ruleId, expression);
            rules.add(rule);

        }

        return rules;
    }



    @RequestMapping("/api/delete_rule")
    @ResponseBody
    public String deleteRule(String rule_id) throws IOException, ClassNotFoundException {
        HashMap<String, String> map = StaticContextV2.getOrRestoreRuleMap();
        map.remove(rule_id);

        return "ok";
    }



    @RequestMapping("/api/trigger_snapshot")
    @ResponseBody
    public String triggerSnapshot() throws IOException, ClassNotFoundException {
        HashMap<String, String> map = StaticContextV2.getOrRestoreRuleMap();

        FileOutputStream out = new FileOutputStream("./rule_snapshot/rules.obj");
        ObjectOutputStream objOut = new ObjectOutputStream(out);

        objOut.writeObject(map);

        return "ok";
    }



}
